import { createRouter, createWebHashHistory } from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: '首页',
    redirect: '/homePage',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/homePage',
        name: '数据总览',
        title: 'dataSummary',
        component: () => import('@/views/homePage/index.vue'),
        meta: { menuName: '数据总览', icon: 'home' }
      },
      {
        path: '/overview/monitor',
        name: 'monitor',
        component: () => import('@/views/overview/MonitorView.vue'),
        meta: { menuName: '实时监测', parent: '城市概览', icon: 'monitor' },
        title: 'cityOverview'
      },
      {
        path: '/overview/analysis',
        name: 'analysis',
        component: () => import('@/views/overview/AnalysisView.vue'),
        meta: { menuName: '统计分析', parent: '环境管理', icon: 'data-analysis' },
        title: 'environmentalManagement'
      },
      {
        path: '/traffic/status',
        name: 'traffic-status',
        component: () => import('@/views/traffic/StatusView.vue'),
        meta: { menuName: '实时路况', parent: '社区管理', icon: 'traffic' },
        title: 'communityManagement'
      },
      {
        path: '/traffic/control',
        name: 'traffic-control',
        component: () => import('@/views/traffic/ControlView.vue'),
        meta: { menuName: '信号灯控制', parent: '交通管理', icon: 'traffic-light' },
        title: 'trafficManagement'
      },
      {
        path: '/environment',
        name: 'environment',
        component: () => import('@/views/EnvironmentView.vue'),
        meta: { menuName: '环境监测', icon: 'environment' },
        title: 'environmentalMonitoring'
      },
      {
        path: '/worker',
        name: 'worker',
        component: () => import('@/views/worker/worker.vue'),
        meta: { menuName: '系统日志', icon: 'worker' },
        title: 'worker'
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫 - 登录验证
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') // 检查登录状态

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
